package option

import (
	"context"
	"strings"
	"time"

	"mall/common/globalkey"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"
	"mall/service/product/model"
	"mall/service/product/rpc/internal/svc"
	"mall/service/product/rpc/internal/utils/errorhandler"
	"mall/service/product/rpc/types/product"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateAttributeOptionLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateAttributeOptionLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateAttributeOptionLogic {
	return &CreateAttributeOptionLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CreateAttributeOptionLogic) CreateAttributeOption(in *product.AttributeOptionInfo) (*product.BaseIDResp, error) {
	// logx.Infof("CreateTerm : %+v ", in)

	if in.AttributeId == nil || *in.AttributeId == 0 {
		return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
	}

	if in.Name == nil || len(strings.TrimSpace(*in.Name)) == 0 {
		return nil, errorx.NewInvalidArgumentError("attribute.optionNameRequired")
	}

	tx, err := l.svcCtx.DB.BeginTx(l.ctx, nil)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	opt := &model.AttributeOption{
		AttributeID: *in.AttributeId,
		Name:        strings.TrimSpace(*in.Name),
	}
	if in.Slug != nil { // 允许为空，不管长度
		opt.Slug = strings.TrimSpace(*in.Slug)
	}
	if in.Sort != nil {
		opt.Sort = uint16(*in.Sort)
	} else {
		opt.Sort = uint16(9999)
	}
	if in.Status != nil {
		opt.Status = uint8(*in.Status)
	} else {
		opt.Status = uint8(globalkey.StatusEnabled)
	}
	now := time.Now()
	opt.CreatedAt = now
	opt.UpdatedAt = now

	err = l.svcCtx.Attribute.InsertOption(l.ctx, tx, opt)
	if err != nil {
		tx.Rollback()
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	tx.Commit()

	return &product.BaseIDResp{
		Id:  opt.OptionID,
		Msg: i18n.CreateSuccess,
	}, nil
}
